package pers.jason.wppm.security.core.authentication.mobile;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * 
 * @author Jason
 * @Date 2018-11-09 15:17
 * 
 *       【自定义security组件】：AuthenticationProvider，用于对从UserDetails获取的用户信息进行校验
 *
 */
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

	private UserDetailsService userDetailsService;

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		// TODO Auto-generated method stub
		SmsCodeAuthenticationToken token = (SmsCodeAuthenticationToken) authentication;
		UserDetails user = userDetailsService.loadUserByUsername((String) token.getPrincipal());
		if (null == user) {
			throw new InternalAuthenticationServiceException("无法获取用户信息");
		}
		// 认证成功后，重新封装用户信息，增加用户权限，认证标志置成true
		SmsCodeAuthenticationToken newToken = new SmsCodeAuthenticationToken(user, user.getAuthorities());
		// 请求信息也封装进去
		newToken.setDetails(token.getDetails());
		return newToken;
	}

	/**
	 * 通过providermanager调用
	 */
	@Override
	public boolean supports(Class<?> authentication) {
		// TODO Auto-generated method stub
		return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
	}

	public UserDetailsService getUserDetailsService() {
		return userDetailsService;
	}

	public void setUserDetailsService(UserDetailsService userDetailsService) {
		this.userDetailsService = userDetailsService;
	}

}
